package com.custom.base.view

import android.content.Context
import android.graphics.Point
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.HorizontalScrollView
import android.widget.LinearLayout

/**
 * 作者：
 * 日期：2020/12/26
 * 说明：左滑控件
 */
class SlideLayout(context: Context?, attrs: AttributeSet? = null) : HorizontalScrollView(context, attrs) {
    private lateinit var mRightMenu: ViewGroup
    private var mOnOpen: OnOpenListener? = null

    /**
     * 右侧菜单宽度
     */
    private var mRightMenuWidth = 0

    /**
     * 滑动超过如下比例，就自动完整显示菜单。
     */
    private var mShowMenuRatio = 0.5
    private var hasMeasured = false

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        /**
         * 显式设置中间内容区域宽度
         */
        if (!hasMeasured) {
            val wrapper = getChildAt(0) as LinearLayout
            val content = wrapper.getChildAt(0) as ViewGroup
            content.layoutParams.width = getScreenWidth()
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        super.onLayout(changed, l, t, r, b)
        if (changed) {
            val wrapper = getChildAt(0) as LinearLayout
            mRightMenu = wrapper.getChildAt(1) as ViewGroup
            mRightMenuWidth = mRightMenu.width
            hasMeasured = true
        }
    }

    /**
     * 左滑动，超过菜单本身宽度一定比例，就完整显示菜单。
     */
    override fun onTouchEvent(ev: MotionEvent): Boolean {
        when (ev.action) {
            MotionEvent.ACTION_UP -> {
                val scrollX = scrollX
                if (scrollX > mRightMenuWidth * mShowMenuRatio) {
                    smoothScrollTo(mRightMenuWidth, 0)
                    mOnOpen?.onOpen(true)
                } else {
                    smoothScrollTo(0, 0)
                    mOnOpen?.onOpen(false)
                }
                return true
            }
        }
        return super.onTouchEvent(ev)
    }

    private fun getScreenWidth(): Int {
        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        val point = Point()
        wm.defaultDisplay.getRealSize(point)
        return point.x
    }

    /**
     * 恢复
     */
    fun open(o:Boolean){
        if(o){
            smoothScrollTo(mRightMenuWidth, 0)
        }else{
            smoothScrollTo(0, 0)
        }
    }

    fun setOpenListener(onOpenListener: OnOpenListener) {
        mOnOpen = onOpenListener
    }

    interface OnOpenListener {
        fun onOpen(open:Boolean)
    }
}